<script setup lang="ts">
import { trimBlank } from '@vc/utils';
import type { FormInstance } from 'element-plus';
import message from 'vc/src/common/message';
import { useUserStore } from '../../../store/modules/user';
import { updatePhone } from '../apis/profile';
import PhoneCode from '../components/phone-code.vue';
import { pageCfg } from '../config';
import { useErrorMess } from '../use';
import UserFormItem from './user-form-item.vue';

interface Props {
  showDialog: boolean;
}

const {
  showDialog
} = defineProps<Props>();

const emit = defineEmits(['update:showDialog']);
const userStore = useUserStore();

// 表单数据
const formData = reactive({
  account: '',
  verifyCode: ''
});

const ruleFormRef = ref<FormInstance>();

const errMess = reactive({
  pwd: '',
  code: '',
  account: ''
});

const { run, loading } = useRequest(updatePhone, {
  manual: true
});

const { cleanMess, handleError } = useErrorMess(errMess);

/** 提交 */
const handleSubmit = async() => {
  await ruleFormRef.value!.validate(async(valid) => {
    if (valid) {
      cleanMess();
      run({
        smsVerifyCode: formData.verifyCode,
        phone: trimBlank(formData.account, 'all')
      }).then((res) => {
        if (res.code === 200 && res.data) {
          message.success('修改成功');
          userStore.setUserInfo({
            ...userStore.getUserInfo,
            phone: trimBlank(formData.account, 'all')
          });
          close();
        } else {
          handleError(res);
        }
      })
      .catch((error) => {
        handleError(error);
      });
    }
  });
};

const close = () => {
  emit('update:showDialog', false);
};
</script>

<template>
  <vc-dialog title="更换手机号" :modelValue="showDialog" @close="close"
    :height="300" :width="468">
    <div class="content">
      <div class="text-14px mb-25px">
        <span class="text-[#242934]">请输入新手机号及验证码</span>
      </div>
      <el-form ref="ruleFormRef" :model="formData" @keypress.enter="handleSubmit">
        <user-form-item v-model:account="formData.account" :placeholder="pageCfg.phonePlaceholder"
          v-model:errorMess="errMess.account" class="phone-input" />
        <phone-code :phone="formData.account" :form="ruleFormRef"
          v-model:verifyCode="formData.verifyCode" v-model:errorMess="errMess.code"
          v-model:errorAccountMess="errMess.account" smsType="updatePhone"
          :formvalidateField="['account']" />
        <el-form-item class="fr">
          <el-button @click="emit('update:showDialog', false)">取消</el-button>
          <el-button :loading="loading" type="primary" color="#02C680" style="color:#FFFFFF;" @click="handleSubmit">确定</el-button>
        </el-form-item>
      </el-form>
    </div>
  </vc-dialog>
</template>

<style lang="scss" scoped>
.content {
  padding: 20px;
  :deep(.phone-input) {
    .vc-input {
      width: 100%;
    }
  }
}
</style>
